package tool

import (
	"log"
)

type Worker struct {
	channel    chan interface{}
	bufferSize int
	customer   func(interface{})
}

func NewWorker(buffersize int, f func(interface{})) *Worker {

	//初始化Worker 并返回
	w := new(Worker)
	w.customer = f
	w.bufferSize = buffersize
	w.channel = make(chan interface{}, buffersize) //初始化时信道缓存
	return w
}

func (w *Worker) Start(num int) {

	for i := 0; i < num; i++ {

		//开启工作go程
		go func() {
			for {
				w.customer(<-w.channel)
			}
		}()

	}

	log.Println("创建了", num, "个工作者线程")

}

func (w *Worker) Post(any interface{}) (bool, int) {

	//这里把信息放入队列
	select {
	case w.channel <- any:
		//返回当前信道缓冲长度,以及总容量

		channelLen := float64(len(w.channel))
		warnLen := float64(w.bufferSize) * 0.8

		//  通道缓存超过80% 报警
		if channelLen >= warnLen {
			SendWarn("CDK服务器报警", "【CDK服务器报警】：通道缓存超过80%")
		}

		return true, len(w.channel)
	default:
		log.Println("Warning: Not Enough Channel Cache, Cancel Request.")
		return false, 0
	}
}

func (w *Worker) GetChannelLength() int {
	return len(w.channel)
}
